package com.sghd.charge.module.payment;

import com.sghd.charge.module.model.OrderInfo;
import com.sghd.charge.module.order.entity.Goods;
import com.sghd.charge.module.order.entity.Order;
import com.sghd.charge.module.order.repository.GoodsRepository;
import com.sghd.charge.module.order.repository.OrderRepository;
import com.sghd.charge.module.utils.Id;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.Optional;

/**
 * @author frank
 */
public abstract class AbstractProcessor implements ChannelProcessor {
    protected final Logger logger = LoggerFactory.getLogger(getClass());
    @Autowired
    protected OrderRepository orderRepository;
    @Autowired
    protected GoodsRepository goodsRepository;
    @Autowired
    protected Id id;

    @Override
    public OrderInfo generateOrder(long playerId, int serverId, String goodsId, String ip) throws Exception {
        //获取商品信息
        Goods goods = getGoods(goodsId);
        //生成订单号
        long orderId = id.nextId();
        //订单金额
        int money = goods.getMoney();
        //附加信息
        String addition = getAddtion(goods, orderId, ip);
        //服务器生成订单
        Order charge = Order.valueOf(serverId, orderId, playerId, money, goodsId, ip, addition, getType());
        orderRepository.save(charge);
        return OrderInfo.valueOf(orderId, money, addition, playerId);
    }

    public abstract String getAddtion(Goods goods, long orderId, String ip) throws Exception;

    public Goods getGoods(String goodsId) throws Exception {
        Optional<Goods> optional = goodsRepository.findById(goodsId);
        if (!optional.isPresent()) {
            throw new IllegalArgumentException("未找到商品信息");
        }
        return optional.get();
    }
}